package com.util.common;

import java.io.File;
import java.io.InputStream;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.Collection;
import java.util.Iterator;

import eu.medsea.mimeutil.MimeUtil;

/**
 * <b>ClassName:<b> MimeUtils
 * <br><b>Description: <br>
 * TODO
 * @Author: kfpanda
 * @Date：2012-1-11 下午10:04:29
 * @ModifyUser：shapecool
 *
 */
public class MimeUtils {
	
	public static Collection<?> getMimeTypes(String fileName){
		MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector");
		Collection<?> mimeTypes = MimeUtil.getMimeTypes(fileName);
		return mimeTypes;
	}
	
	public static Collection<?> getMimeTypes(File file){
		MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector");
		Collection<?> mimeTypes = MimeUtil.getMimeTypes(file);
		return mimeTypes;
	}
	
	public static Collection<?> getMimeTypes(InputStream inputStream){
		MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector");
		Collection<?> mimeTypes = MimeUtil.getMimeTypes(inputStream);
		return mimeTypes;
	}
	
	public static String getMimeType(String fileName){
		String type = null;
		Collection<?> mimeTypes = getMimeTypes(fileName);
		for(Iterator<?> itr = mimeTypes.iterator(); itr.hasNext();){
			type = itr.next().toString();
			break;
		}
		return type;
	}
	
	public static String getMimeType(File file){
		String type = null;
		Collection<?> mimeTypes = getMimeTypes(file);
		for(Iterator<?> itr = mimeTypes.iterator(); itr.hasNext();){
			type = itr.next().toString();
			break;
		}
		return type;
	}
	
	public static String getMimeType(InputStream inputStream){
		String type = null;
		Collection<?> mimeTypes = getMimeTypes(inputStream);
		for(Iterator<?> itr = mimeTypes.iterator(); itr.hasNext();){
			type = itr.next().toString();
			break;
		}
		return type;
	}
	
	private String test(String fileUrl){
		String type = null;
//	    URL u = new URL(fileUrl);
//	    URLConnection uc = null;
//	    uc = u.openConnection();
//	    uc.getContentEncoding();
//	    type = uc.getContentType();
	    
	    FileNameMap fileNameMap = URLConnection.getFileNameMap();
	    type = fileNameMap.getContentTypeFor(fileUrl);

	    return type;
	}
}
